﻿package net.wangit.dev.unit;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.enumeration.EnumerationUtil;
import net.wangit.view.tree.TreeUtil;
import net.wangit.view.unit.UnitComponent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class UnitUI implements UnitInterceptor {

	private static final Log log = LogFactory
			.getLog(net.wangit.dev.unit.UnitUI.class);
	private static final String QUOTE = "&quot;";
	public static final String KEY = "net.wangit.dev.unit.UnitUI.unitid";
	private static final String SQL_UNIT = "select * from UNIT where uid=?";
	private static final String SQL_ELEMENT = "select * from ELEMENT where uid=? order by b,o";
	private static final String SQL_PARENT = "select uid as value ,uid+' - '+ti as name,pid from UNIT where c!=7 and uid!=? order by uid";
	private static final String SQL_PARENT_ADD = "select uid as value ,uid+' - '+ti as name,pid from UNIT where c!=7 order by uid";

	public UnitUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		DB db = DBHelper.getDomainDB(domain);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String unitId = copy ? source : getUnitId(ac);
		String unitShowMode = unit.getShowMode();
		Unit u = (Unit) unit.getElement("unit").getObject();
		UnitComponent e = (UnitComponent) unit.getElement("element")
				.getObject();
		e.setRowsVisible(false);
		u.getElement("pid").setObject(
				getParentUnitEnumeration(db, unitId, unitShowMode));
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			u.getElement("gid").setDefaultValue(groupId);
			String parentUnitId = ac.getRequestParameter("parentid");
			u.getElement("pid").setDefaultValue(parentUnitId);
		} else if (unit.getData() == null) {
			MapList unitData = db.query(UnitUI.SQL_UNIT, unitId, 2);
			unit.setData(unitData);
			u.setData(unitData);
			MapList elementData = db.query(UnitUI.SQL_ELEMENT, unitId, 2);
			e.setData(elementData);
			if (copy) {
				unitData.put(0, "uid", "");
				unitData.put(0, "l", "0");
				unitData.put(0, "y", "0");
			} else if ("e".equals(unitShowMode))
				unit.getElement("import").setCustom(
						(new StringBuilder(
								"onclick=doLink('/dev/unit.import.do?uid="))
								.append(unitId).append("')").toString());
		}
		int unitType = ac.getRequestParameterInt("c", -1);
		MapList data;
		if (unitType < 0) {
			data = unit.getData();
			if (!Checker.isEmpty(data)) {
				unitType = data.getRow(0).getInt("c", 1);
			} else {
				log.warn("could not set uc, FormUnit was used.");
				unitType = 1;
			}
		} else {
			unit.getElement("c").setDefaultValue(Integer.toString(unitType));
		}
		filterElements(unitType, unit, u, e);
		data = unit.getData();
		if (data != null) {
			data.put(0, "domain", domain);
		} else {
			data = new MapList();
			data.put(0, "domain", domain);
			unit.setData(data);
		}
		LockUtil.setElements(ac, u, new Object[][] { new Object[] { unit,
				"import", "save" } });
		convertQuote(e);
		return unit.write(ac);
	}

	private void convertQuote(UnitComponent elementUnit) {
		MapList elementData = elementUnit.getData();
		if (!Checker.isEmpty(elementData)) {
			for (int i = 0; i < elementData.size(); i++) {
				convertQuote(i, elementData, "cu");
				convertQuote(i, elementData, "wp");
				convertQuote(i, elementData, "ws");
				convertQuote(i, elementData, "wcu");
			}

		}
	}

	private void convertQuote(int index, MapList elementData, String name) {
		String value = elementData.getRow(index).get(name);
		if (!Checker.isEmpty(value))
			elementData.put(index, name, StringUtil.replace(value, "\"",
					UnitUI.QUOTE));
	}

	public static String getUnitId(ActionContext ac) {
		return ActionContextHelper.getRequest2Session(ac, "uid", UnitUI.KEY,
				null);
	}

	private MapList getParentUnitEnumeration(DB db, String unitId,
			String showMode) {
		try {
			MapList list;
			if ("a".equals(showMode))
				list = db.query(UnitUI.SQL_PARENT_ADD);
			else
				list = TreeUtil.filterParentId(db, UnitUI.SQL_PARENT, unitId,
						"pid", 2);
			if (Checker.isEmpty(list))
				list = new MapList();
			list.insertRow(0, EnumerationUtil.getBlankRow());
			return list;
		} catch (Exception e) {
			log.error((new StringBuilder("create Unit Enumeration failed:"))
					.append(e).toString());
			return null;
		}
	}

	private void filterElements(int unitType, Unit unit, Unit u, Unit e) {
		switch (unitType) {
		case 1:
			u.removeGroup("l");
			e.removeElement("ls");
			e.removeElement("qm");
			e.getElement("n").setTdColSpan(3);
			break;

		case 2:
			u.removeElement("x");
			unit.getElement("la").setShowMode(7);
			unit.getElement("g").setShowMode(7);
			u.removeElement("ma");
			e.removeElement("qm");
			e.removeElement("ma");
			e.getElement("me").setSuffix("(查看/修改)");
			break;

		case 3:
			u.removeGroup("l");
			u.removeElement("x");
			u.removeElement("t");
			u.removeElement("d");
			u.removeElement("dm");
			u.removeElement("dpid");
			u.removeElement("de");
			u.removeElement("ms");
			u.removeElement("ma");
			u.getElement("pp").setTdColSpan(3);
			Element unitEditShowMode = u.getElement("me");
			unitEditShowMode.setShowMode(7);
			unitEditShowMode.setSuffix(null);
			u.removeElement("r");
			u.removeElement("i3");
			u.removeElement("rc");
			u.removeElement("v7");
			u.removeElement("ais");
			e.removeElement("ls");
			e.removeElement("ma");
			e.removeElement("ms");
			Element elementEditShowMode = e.getElement("me");
			elementEditShowMode.setTdColSpan(1);
			elementEditShowMode.setCss("s2");
			break;
		}
	}

}
